package org.lites.dcimmodifier;


import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.textview.MaterialTextView;
import com.osard.editspinner.SimpleAdapter;
import org.lites.dcimmodifier.databinding.ActivityMainBinding;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import static org.lites.dcimmodifier.Constants.myPath;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    private final String root_dir = "/storage/emulated/";
    private final String storage_main_dir = root_dir + "0/";
    private final String storage_999_dir = root_dir + "999/";
    private DrawRecyclerInfo drawRecyclerInfo = null;


    private RecyclerView recyclerview;
    private TextView textview_first_tv;
    private Button numbt_bt;
    private AppCompatEditCallbackSpinner numacecsp = null;
    private SimpleAdapter numspitemadapter;
    private List<String> numspitemlist = new ArrayList<>();
    private PermissionsMaker.PermissionsHandler permissionsHandler;
    private PermissionsMaker permissionsMaker;

    private TextView numplaysp;
    private Button playbt;
    private Button stopbt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        permissionsHandler = new PermissionsMaker.PermissionsHandler() {
            @Override
            public void excute() {
                authed_execute();
            }
        };
        permissionsMaker = new PermissionsMaker(this, permissionsHandler);

    }

    private void initView() {
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        textview_first_tv = findViewById(R.id.textview_first);
        textview_first_tv.setText("");
        numbt_bt = findViewById(R.id.numbt);
        playbt = findViewById(R.id.playbt);
        stopbt = findViewById(R.id.stopbt);


        numbt_bt.setOnClickListener(v -> {

            // 在子线程中执行耗时任务
            new Thread(() -> {
                File path = new File(numacecsp.getEditText().getText().toString().replace("\r", "").replace("\n", ""));
                List<File> imgpathlist = FileTraverser.getFileList(path, Constants.TYPE_ALL, 1);
                runOnUiThread(() ->numplaysp.setText(":" + imgpathlist.size()));
                DrawAllRecyclerView(imgpathlist);
            }).start();
        });


        playbt.setOnClickListener(v -> {
                // 在子线程中执行耗时任务
                new Thread(() -> {

                    String[] filepathlist = drawRecyclerInfo.getPath();

                    runOnUiThread(() -> playbt.setText("执行中"));// 在主线程中更新 TextView

                    runOnUiThread(() -> playbt.setEnabled(false));// 在主线程中更新 TextView
                    for (int i = 0; i < filepathlist.length; i++) {
                        String filePath = filepathlist[i];
                        int finalI = i;
                        runOnUiThread(() -> numplaysp.setText(":" + (finalI + 1) + "/" + filepathlist.length));// 在主线程中更新 TextView
                        String details = ImageUtils.imageInfoGetter(filePath).trim();
                        if (!details.equals("")) {
                            String[] timelist = details.split("->");
                            String beforetimestr = timelist[0].trim();
                            String aftertimestr = timelist[1].trim();
                            if (!beforetimestr.equals(aftertimestr)) {
                                ImageUtils.imageTimeModifier(filePath, aftertimestr);
                            }
                        }
                    }
                    runOnUiThread(() ->ToastUtils.showLong(MainActivity.this, "完成日期修改！"));
                    runOnUiThread(() -> playbt.setEnabled(true));// 在主线程中更新 TextView
                    runOnUiThread(() -> playbt.setText("执行"));// 在主线程中更新 TextView
                }).start();


            }
        );
        stopbt.setOnClickListener(v -> {
//                mp.stopPlay();
//                playbt.setVisibility(View.VISIBLE);
//                stopbt.setVisibility(View.GONE);
//                lastbt.setVisibility(View.GONE);
//                nextbt.setVisibility(View.GONE);
//                // 启用RadioGroup及其内部的RadioButton
//                playselrg.setEnabled(true);
//                for (int i = 0; i < playselrg.getChildCount(); i++) {
//                    playselrg.getChildAt(i).setEnabled(true);
//                }
//                numplaysp.setEnabled(true);
        });


        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
//        binding.fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                Snackbar.make(view, String.format(Locale.CHINESE,"qmc_dir:%s\r\nflac_dir: %s\r\n",qmcPath,flacPath), Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
////                Toast.makeText(MainActivity.this,String.format(Locale.CHINESE,"qmc_dir:%s\r\nflac_dir: %s\r\n",qmcPath,flacPath),Toast.LENGTH_LONG).show();
//            }
//        });
    }

    private void authed_execute() {

        initView();
        initCopyConfig();
        CopyConfig();
        setSpinner();
        File path = new File(storage_main_dir);
        List<File> imgpathlist = FileTraverser.getFileList(path, Constants.TYPE_ALL, 1);
        numplaysp.post(() -> numplaysp.setText(":" + imgpathlist.size()));
        DrawAllRecyclerView(imgpathlist);


    }

    /***
     * 所有需要复制到本地的配置文件可以在这里添加，已经提供几种类型文件参考复制方式
     */
    private void CopyConfig() {
        try {
            File outpath = new File(myPath);

            if (!outpath.exists()) {
                outpath.mkdirs();
            }
//            File outfile = new File(myPath + File.separator + configname);//复制json配置文件到本地
//            if (!outfile.exists()) {
//                try {
//                    outfile.createNewFile();
//                    InputStream myInput = this.getAssets().open(configname);
//                    OutputStream myOutput = new FileOutputStream(outfile);
//                    byte[] buffer = new byte[1024 * 8];
//                    int length = myInput.read(buffer);
//                    while (length > 0) {
//                        myOutput.write(buffer, 0, length);
//                        length = myInput.read(buffer);
//                    }
//                    myOutput.flush();
//                    myInput.close();
//                    myOutput.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }

//            File musicfolder = new File(myPath + File.separator + musicfoldername);//复制压缩包到本地
//            if (!musicfolder.exists() ||musicfolder.listFiles()==null||musicfolder.listFiles().length==0) {
//                musicfolder.mkdirs();
//                ZipUtils.UnZipAssetsFolder(this,musiczipname+".zip",myPath + File.separator + musicfoldername);
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 获取storage_main_dir目录下的子层文件路径
     * @return 子层文件路径
     */
    private List<String> getFileDirs() {
        return getFileDirs(storage_main_dir);
    }

    /***
     * 获取pathStr目录下的子层文件路径
     * @param pathStr 目录路径
     * @return 子层文件路径
     */
    private List<String> getFileDirs(String pathStr) {
        List<String> filenamelist = new ArrayList<>();
        // 读取外部存储的文件和文件夹
        File rootDir = new File(pathStr);  // 通常是内部存储的根目录
        return FileTraverser.getDirStringList(rootDir, 1);
    }

    /***
     * 删除path下的所有文件和子文件
     * @param path 路径
     */
    public void deleteDirectory(String path) {
        File directory = new File(path);

        if (directory.exists()) { // 判断路径是否存在
            File[] files = directory.listFiles(); // 获取该目录下的所有文件或子目录

            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) { // 若为子目录则进行递归调用
                    deleteDirectory(files[i].getAbsolutePath());
                } else { // 若为文件直接删除
                    files[i].delete();
                }
            }

            directory.delete(); // 最后删除空目录
        }
    }

    /***
     * 初始化配置文件处理
     */
    private void initCopyConfig() {

        SharedPreferences preferences = getSharedPreferences("FirstStart", MODE_PRIVATE);
        int FirstStart = preferences.getInt("FirstStart", 0);
        System.out.println(String.format("FirstStart:%d", FirstStart));
        if (FirstStart == 0) {//第一次安装应用
            //************配置文件拷贝到本地*****************************
            deleteDirectory(myPath);
            CopyConfig();
        }
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("FirstStart", 1);
        editor.commit();

    }

    /***
     * 获取系统语言
     * @return 系统语言
     */
    private String getLanguage() {
        // 步骤1：获取系统的Locale
        Locale systemLocale = Locale.getDefault();
        // 步骤2：获取应用的Configuration
        Configuration appConfig = getResources().getConfiguration();
        // 步骤3：获取应用的Locale
        Locale appLocale = appConfig.locale;
        // 步骤4：获取应用设置的语言
        String appLanguage = appLocale.getLanguage();
        return appLanguage;
    }

    /**
     * 为num串添加换行符
     * @param num  字符串
     * @return 添加换行符后的字符串
     */
    private String addNewLineChar(String num){
        String showpath=num;
        if (num.length() > Constants.MAXCHAR) {
            StringBuilder formattedString = new StringBuilder();
            int start = 0;

            // 每maxwidth个字符添加一个换行符
            while (start + Constants.MAXCHAR < num.length()) {
                formattedString.append(num, start, start + Constants.MAXCHAR); // 获取从start到start+maxwidth的子字符串
                formattedString.append("\r\n"); // 添加换行符
                start += Constants.MAXCHAR; // 更新start位置
            }

            // 添加剩余部分（如果有不足maxwidth个字符的部分）
            formattedString.append(num.substring(start));

            showpath = formattedString.toString();
        }
        return showpath;
    }
    /***
     * 设置spinner
     */
    private void setSpinner() {
        numspitemlist = getFileDirs();
        numacecsp = findViewById(R.id.numsp);
        numspitemadapter = new SimpleAdapter(this, numspitemlist);
        numacecsp.setAdapter(numspitemadapter);
        numplaysp = findViewById(R.id.numplay);
        numacecsp.addItemClickCallBack((ItemClickCallBack) (parent, view, position, id) -> {
            String num = ((MaterialTextView) view).getText().toString();
            String finalNum = addNewLineChar(num);
            runOnUiThread(() ->numacecsp.setText(finalNum));
            new Thread(() -> {
                if (view instanceof MaterialTextView) {
                    int ind = numspitemlist.indexOf(num);
                    if (ind != -1) {
                        runOnUiThread(() ->ToastUtils.showLong(this, ind + ":" + num));
                        numspitemlist = getFileDirs(num);
                        numspitemadapter = new SimpleAdapter(this, numspitemlist);
                        runOnUiThread(() ->numacecsp.setAdapter(numspitemadapter));
                    }
                }
            }).start();

        });
        numacecsp.addTextChangeCallBack((TextChangeCallBack) (s, start, before, count) -> {
            String now_path = s.toString().trim().replace("\r", "").replace("\n", "");
            now_path = now_path.substring(0, now_path.lastIndexOf(File.separator));
            String finalNow_path = now_path;
            new Thread(() -> {
                if (start != 0) {
                    if (root_dir.contains(finalNow_path) && !root_dir.equals(finalNow_path)) {
                        runOnUiThread(() ->numacecsp.setText(root_dir));
                        numspitemlist = Arrays.asList(storage_main_dir, storage_999_dir);
                        numspitemadapter = new SimpleAdapter(this, numspitemlist);
                        runOnUiThread(() ->numacecsp.setAdapter(numspitemadapter));
                    } else {
                        numspitemlist = getFileDirs(finalNow_path);
                        numspitemadapter = new SimpleAdapter(this, numspitemlist);
                        runOnUiThread(() ->numacecsp.setAdapter(numspitemadapter));
                    }
                }
            }).start();

        });
        numacecsp.post(() -> numacecsp.setText(storage_main_dir));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    /**
     * 处理recyclerview信息并绘制
     * @param imgpathlist 图片路径列表
     */
    private void DrawAllRecyclerView(List<File> imgpathlist) {
        String[] numspitemarr = new String[imgpathlist.size()];
        for (int i = 0; i < imgpathlist.size(); i++) {
            numspitemarr[i] = "" + (i + 1);
        }
        String[] musicspitemarr = new String[imgpathlist.size()];
        for (int i = 0; i < imgpathlist.size(); i++) {
            musicspitemarr[i] = imgpathlist.get(i).getName();
        }
        String[] cropitemarr = new String[imgpathlist.size()];
        for (int i = 0; i < imgpathlist.size(); i++) {
            cropitemarr[i] = imgpathlist.get(i).getPath();
        }

        drawRecyclerInfo = new DrawRecyclerInfo(numspitemarr, musicspitemarr, cropitemarr);
        DrawRecyclerView(drawRecyclerInfo);
    }

    /**
     * 绘制recyclerview
     * @param drawRecyclerInfo recyclerview信息
     */
    private void DrawRecyclerView(DrawRecyclerInfo drawRecyclerInfo) {
        //新建一个RecyclerView的适配器，并传入数据
        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(this, drawRecyclerInfo);
        //将适配器设置给recyclerview控件
        runOnUiThread(() ->recyclerview.setAdapter(recyclerViewAdapter));
        //新建一个StaggeredGridLayoutManager布局管理器，设置参数：1.显示的列数   2.显示布局的方向（水平或垂直）
        //StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
        //将布局管理器设置给recyclerveiw控件
        //recyclerview.setLayoutManager(staggeredGridLayoutManager);
        runOnUiThread(() ->recyclerview.setLayoutManager(linearLayoutManager));
//        //给适配器添加我们暴露的监听方法
//        recyclerViewAdapter.setOnRecyclerViewItemClickListener(this);

    }

/*    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        permissionsMaker.onRequestPermissionsResult(requestCode,permissions,grantResults);

    }*/


}
